package com.nativetalk.controller.app.member;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberLogin;
import com.nativetalk.bean.member.TdNtMemberRegister;
import com.nativetalk.bean.member.TdNtMemberRetrieve;
import com.nativetalk.bean.sms.Sms;
import com.nativetalk.common.Constants;
import com.nativetalk.common.Lang;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.Ip;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dto.MemberLoginByCode;
import com.nativetalk.dto.MemberRegisterByCode;
import com.nativetalk.dto.account.UpdateDeviceIdDto;
import com.nativetalk.service.member.login.MemberLoginService;
import com.nativetalk.service.member.register.MemberRegisterService;
import com.nativetalk.service.member.retrieve.MemberRetrieveService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 15/12/9.
 */
@Controller
public class MemberController {
    private static Logger logger = Logger.getLogger(MemberController.class);
    @Resource
    private MemberRegisterService memberRegisterService;
    @Resource
    private MemberLoginService memberLoginService;
    @Resource
    private MemberRetrieveService memberRetrieveService;

    /**
     * @param tdNtMemberLogin
     * @return RetInfo
     * @Purpose 登陆
     * @version 1.0
     * @time 2015-12-24
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/login", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo login(HttpServletRequest request, @Valid @RequestBody TdNtMemberLogin tdNtMemberLogin, BindingResult result,
                         @RequestHeader(value = "client_type", required = true) String client_type,
                         @RequestHeader(value = "version", required = true) Integer version) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(tdNtMemberLogin));

            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                if (version >= 6) {
                    tdNtMemberLogin.setEqu_type(client_type);
                    retInfo = memberLoginService.login(tdNtMemberLogin, version, Ip.getIpAddr(request));
                } else {
                    retInfo.setMark("1");
                    retInfo.setTip("请更新最新版本");
                }

            }
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param tdNtMemberRegister
     * @return RetInfo
     * @Purpose 注册
     * @version 1.0
     * @time 2015-12-22
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/register", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo register(@Valid @RequestBody TdNtMemberRegister tdNtMemberRegister, BindingResult result,
                            @RequestHeader(value = "client_type", required = true) String client_type,
                            @RequestHeader(value = "version", required = true) Integer version) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(tdNtMemberRegister));
            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                tdNtMemberRegister.setEqu_type(client_type);
                retInfo = memberRegisterService.register(tdNtMemberRegister, version);

            }
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param tdNtMemberRegister
     * @return RetInfo
     * @Purpose 注册
     * @version 1.0
     * @time 2015-12-22
     * @author lizhun
     */
    @RequestMapping(value = "/app/5/member/register", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo register5(@Valid @RequestBody TdNtMemberRegister tdNtMemberRegister, BindingResult result,
                             @RequestHeader(value = "client_type", required = true) String client_type,
                             @RequestHeader(value = "version", required = true) Integer version) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(tdNtMemberRegister));

            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                tdNtMemberRegister.setEqu_type(client_type);
                retInfo = memberRegisterService.register(tdNtMemberRegister, version);
            }

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param sms
     * @return RetInfo
     * @Purpose 注册
     * @version 1.0
     * @time 2015-12-22
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/registerSms", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json; charset=utf-8")
    @ResponseBody
    public RetInfo registerSms(@Valid @RequestBody Sms sms, BindingResult result) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(sms));

            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                retInfo = memberRegisterService.smsRegister(sms);
            }

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(Lang.ZH);
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param sms
     * @return RetInfo
     * @Purpose 找回密码发送短信
     * @version 1.0
     * @time 2015-12-24
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/retrievePsdSms", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo retrievePsdSms(@Valid @RequestBody Sms sms, BindingResult result) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(sms));

            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                retInfo = memberRetrieveService.retrieveSms(sms);
            }

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


    /**
     * @param sms
     * @return RetInfo
     * @Purpose 通过验证码注册登录发送短信验证码
     * @version 1.0
     * @time 2015-12-24
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/registerAndLogin/ByCode", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo RegisterAndLoginByCode(@Valid @RequestBody Sms sms, BindingResult result) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(sms));

            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                retInfo = memberRetrieveService.retrieveByCodeSms(sms);
            }

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param tdNtMemberRetrieve
     * @return RetInfo
     * @Purpose 找回密码
     * @version 1.0
     * @time 2015-12-24
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/member/retrievePsd", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo retrievePsd(@Valid @RequestBody TdNtMemberRetrieve tdNtMemberRetrieve, BindingResult result) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(tdNtMemberRetrieve));
            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                retInfo = memberRetrieveService.retrieve(tdNtMemberRetrieve);
            }
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param token
     * @return RetInfo
     * @Purpose 退出
     * @version 1.0
     * @time 2015-01-05
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/out", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo out(@RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_out);
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            RetInfo retInfo = memberLoginService.out(tdNtMember);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @param token
     * @return
     * @Purpose 更新学生的deviceId（设备id）,当用户程序在后台运行一段时间，这时用户退出再次登录的时候，有可能丢失deviceId，这时客户端通过调用该方法补充deviceId
     * @version 4.1
     * @author Peter
     * @date 2017-03-20
     */
    @RequestMapping(value = "/app/11/token/member/deviceid/update",
            method = {RequestMethod.GET, RequestMethod.POST},
            consumes = "application/json")
    @ResponseBody
    public RetInfo updateEquClientId(@RequestBody UpdateDeviceIdDto request,
                                     @RequestHeader(value = "token", required = true) String token,
                                     @RequestHeader(value = "client_type", required = true) String client_type) {
        try {
            //打印入参
            logger.info(Constants.prefix_out);
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            RetInfo retInfo = memberLoginService.updateEquClientId(tdNtMember.getMemb_id(), request.getEqu_client_id(), client_type);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 通过注册码登录
     * @param memberLoginByCode
     * @param result
     * @param client_type
     * @param version
     * @return
     */
    @RequestMapping(value = "/app/1/member/login/bycode", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo loginBycode(@Valid @RequestBody MemberLoginByCode memberLoginByCode, BindingResult result,
                               @RequestHeader(value = "client_type", required = true) String client_type,
                               @RequestHeader(value = "version", required = true) Integer version) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(memberLoginByCode));
            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                memberLoginByCode.setEqu_type(client_type);
                retInfo = memberRegisterService.loginByCode(memberLoginByCode, version);

            }
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
    /**
     * 通过注册码注册
     * @param memberLoginByCode
     * @param result
     * @param client_type
     * @param version
     * @return
     */
    @RequestMapping(value = "/app/1/member/register/bycode", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo registerBycode(@Valid @RequestBody MemberRegisterByCode memberLoginByCode, BindingResult result,
                                  HttpServletRequest request,
                                  @RequestHeader(value = "client_type", required = true) String client_type,
                                  @RequestHeader(value = "version", required = true) Integer version) {
        try {
            //打印入参
            logger.info(Constants.prefix_out + JsonUtil.toJson(memberLoginByCode));

            MemberRegisterByCode memberRegisterByCode = new MemberRegisterByCode();
            memberLoginByCode.setInvite_code(request.getParameter("invite_code"));
            memberLoginByCode.setMemb_phone(request.getParameter("memb_phone"));
            memberLoginByCode.setMemb_phone_area(request.getParameter("memb_phone_area"));
            RetInfo retInfo = new RetInfo();
            if (result.hasErrors()) {
                List<FieldError> err = result.getFieldErrors();
                FieldError fe = err.get(0);
                retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
                retInfo.setTip(fe.getDefaultMessage());
            } else {
                retInfo = memberRegisterService.registerByCode(memberLoginByCode, version);

            }
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 重新获取融云token（学生）
    @RequestMapping(value = "/v5.0/student/token/account/receiveRongCloudToken", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json; charset=utf-8")
    @ResponseBody
    public RetInfo receiveRongCloudToken(@RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(Constants.prefix_in);
            //打印入参
            logger.info(Constants.prefix_out);
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;
            RetInfo retInfo = RetInfo.getSuccessInfo();
            String rongCloudToken = memberLoginService.receiveRongCloudTokenForStudent(tdNtMember.getMemb_id());
            Map<String, String> map = new HashMap<>();
            map.put("rongCloudToken", rongCloudToken);
            retInfo.setObj(map);
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


}


